/*!
 @header AuthCodeFormViewController.m
 @author 周益
 @version 1.0.0 2013/01/28 Creation
 Copyright (c) 2013年 mypocketbaby. All rights reserved.
 */

#import "AuthCodeFormViewController.h"
#import "Config.h"
#import "Helper.h"
#import "PasswordFormViewController.h"
#import "JMFBase.h"


//  -业务逻辑细节说明-
//
//  @abstract       AuthCodeFormViewController功能较为简单，只涉及到NSTimer的运用。用于填写和重新发送短信认证号码。
//

//  @discussion     NSTimer的scheduledTimerWithTimeInterval:方法的运用。设置为每一秒执行一次回调方法即可
//               (详见方法“handleTimer:” “initTimer” "stopTimer")。

//  @notes          注意在返回按钮和验证验证码成功后要停止计时，避免再次回到此view中，_sec会不正常计时。


//  -类修改日志-
//  修改人   修改时间   针对版本   修改描述

@interface AuthCodeFormViewController ()

@end

@implementation AuthCodeFormViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)init
{
    self = [super init];
    if (self) {
        _sec = _CODE_SEND_RELAY;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    //背景颜色
    self.view.backgroundColor = _SYS_COLOR_BACKGROUND;
    
    //标题
    self.title = _L(@"vc_title_059");

    //返回按钮
    UIButton *backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    //label
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 25, 140, 20)];
    label.backgroundColor = [UIColor clearColor];
    label.font = _SYS_FONT_004;
    label.textColor = _SYS_COLOR_002;
    label.text = _L(@"title_49");
    [self.view addSubview:label];
    
    //电话号码
    UILabel *phoneLabel = [[UILabel alloc] init];
    CGRect labelRect = CGRectMake(145, 25, 150, 25);
    phoneLabel.frame = labelRect;
    phoneLabel.font = _SYS_FONT_009;
    
    //将手机号码设置为用户输入过的
    phoneLabel.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"accountMobile"];
    phoneLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:phoneLabel];
    
    //验证码输入框背景
    UIImageView *textFieldImageView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_bg_009@2x" ofType:@"png"]]];
    textFieldImageView.frame = CGRectMake(10, 60, 140, 43);
    [self.view addSubview:textFieldImageView];
    
    //验证码输入框
    _textField = [Helper textField:CGRectMake(15, 61, 130, 40) byPlaceholder:_L(@"holder_17")];
    _textField.font = _SYS_FONT_007;
    _textField.keyboardType = UIKeyboardTypePhonePad;
    [_textField becomeFirstResponder];
    [self.view addSubview:_textField];
    
    //计时view
    [self renderTimerView];
    
    //下一步按钮
    UIButton *nextButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 130, 300, 44)];
    [nextButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [nextButton setTitle:_L(@"btn_yes_11") forState:UIControlStateNormal];
    [nextButton setBackgroundImage:[UIImage imageNamed:@"com_btn_006_n"] forState:UIControlStateNormal];
    [nextButton addTarget:self action:@selector(nextButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    nextButton.titleLabel.font = _SYS_FONT_009;
    [self.view addSubview:nextButton];
    
    //开始计时
    [self initTimer];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - 私有方法

/*!
 @abstract 绘制出timerview
 */
- (void)renderTimerView
{
    //计时view
    _timerView = [[TimerView alloc] initWithFrame:CGRectMake(155, 60, 155, 43)];
    _timerView.backgroundColor = [UIColor clearColor];
    _timerView.secLabel.text = [NSString stringWithFormat:@"%d", _CODE_SEND_RELAY];
    [self.view addSubview:_timerView];
}

/*!
 @abstract 初始化一个nstimer，用于计时
 */
- (void)initTimer
{
    _timer = [NSTimer scheduledTimerWithTimeInterval: 1.0f
                                              target:self
                                            selector: @selector(handleTimer:)
                                            userInfo:nil
                                             repeats:YES];
}

/*!
 @abstract 停止计时，并且绘制出重新发送的按钮
 */
- (void)stopTimer
{
    //停止计时
    [_timer invalidate];
    
    //将_label移除，绘制成button
    [_timerView removeFromSuperview];
    
    _resendButton = [[UIButton alloc] initWithFrame:CGRectMake(155, 60, 155.5, 42.5)];
    _resendButton.titleLabel.font = _SYS_FONT_009;
    _resendButton.backgroundColor = [UIColor clearColor];
    [_resendButton setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"user_bg_002@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [_resendButton addTarget:self action:@selector(resendButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_resendButton];
}


/*!
 @abstract 回调：每一秒执行一次。
 当计时为0时，就要结束计时，准备下一次计时
 当计时大于0并且不小于10时，每一秒刷新一下secLabel的值
 当_sec分别为一位数和两位数时，lable宽度居中显示
 */
- (void)handleTimer:(NSTimer *)theTimer
{
    //当_sec为0时，那么停止timer；重新发送按钮应该enable。
    if (_sec == 0) {
        
        [self stopTimer];
        
    }else{
        
        //当_sec大于0的时候，一直计时
        _timerView.secLabel.text = [NSString stringWithFormat:@"%d", --_sec];
        
        //当_sec分别为一位数和两位数时，lable宽度居中显示
        if (_sec < 10) {
            
            _timerView.secLabel.frame = CGRectMake(13, 13, 15, 20);
            
        }else if (_sec < 100 && _sec > 9){
            
            _timerView.secLabel.frame = CGRectMake(8, 13, 35, 20);
        }
    }
}

/*!
 @abstract 验证认证号码
 */
- (BOOL)validateAuthCode:(NSString *)mobile
{
    NSString *codeRegex = @"^[A-Z0-9]{6}$";;
    NSPredicate *authCodeTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",codeRegex];
    return [authCodeTest evaluateWithObject:mobile];
}



#pragma mark - 自定义事件
 
/*!
 @abstract 重发一次验证码，绘制出计时label，并激活NSTimer
 */
- (void)resendButtonEvent:(id)sender
{
    //设置下一次开始计时的数
    _sec = _CODE_SEND_RELAY;
    
    //下一次计时开始，去除重新发送按钮
    [_resendButton removeFromSuperview];
    
    //重新绘出文本
    //计时view
    [self renderTimerView];
    
    //重新计时
    [self initTimer];
    
    //向服务器发送获取验证码请求
    JSONRequest *authCodeRequest = [[JSONRequest alloc] initWithURLString:_JSON_URL_U_GET_CODE];
    NSString *mobile = [[NSUserDefaults standardUserDefaults] objectForKey:@"accountMobile"];
    [authCodeRequest setValue:mobile forParameter:@"mobile"];
    NSDictionary *responseData = [authCodeRequest synchronous];
    
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:responseData];
    //重新获得验证码失败就显示失败原因。成功则什么也不做
    if (jmf.status != JMStatusSucceed) {
        [Helper easyShowJMFStatus:jmf];
    }
}

/*!
 @abstract 返回按钮事件
 */
- (void)backButtonEvent:(id)sender
{
    [self stopTimer];
    
    [self.navigationController popViewControllerAnimated:YES];
}


/*!
 @abstract 下一步按钮事件
 */
- (void)nextButtonEvent:(id)sender
{
    //验证码，6位，由数字或大写字母组成
    if ([_textField.text length] == 6 && ([self validateAuthCode:_textField.text])) {
        
        //验证手机和验证码，成功，下一步设置密码；失败，提示信息
        JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_U_CHECK_CODE];
        request.delegate = self;
        request.hudOn = true;
        request.hudTitle =_L(@"title_loading_12");  //正在比对验证码
        
        NSString *mobile = [[NSUserDefaults standardUserDefaults] objectForKey:@"accountMobile"];
        [request setValue:mobile forParameter:@"mobile"];
        [request setValue:_textField.text forParameter:@"code"];
        [request asynchronous];
    }
    else {
        [Helper showAlertWithTitle:nil andMessage:_L(@"alert_41")];   //验证码输入错误，请重新输入
    }
    
}


#pragma mark - JSONRequestDelegate

//
- (void)requestDidLoadJSON:(NSDictionary *)responseData
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:responseData];

    if (jmf.status == JMStatusSucceed) {
        //暂存验证码
        [[NSUserDefaults standardUserDefaults] setValue:_textField.text forKey:@"code"];
        //跳转页面
        PasswordFormViewController *passwordFormVC = [[PasswordFormViewController alloc] init];
        
        if ([[NSUserDefaults standardUserDefaults] boolForKey:@"isRegisterOrNot"] == YES) {
            [passwordFormVC.navigationItem setTitle:_L(@"vc_title_060")];   //设置密码
        
        }else{
            [passwordFormVC.navigationItem setTitle:_L(@"vc_title_061")];   //设置新密码
        }
        
        [self.navigationController  pushViewController:passwordFormVC animated:YES];
        
        [self stopTimer];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

//
- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}

@end
